﻿using GN.Pay.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.TradeChannel.Gyb.Response
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class AXmlResponse : AResponse
    {
        private static string Format_ErrorMessage = "响应结果格式不正确，接口响应出错!";
        protected readonly ITradeChannel channel;
        protected readonly GybConfigure config;
        protected string signature;
        protected string plain;

        public AXmlResponse(string responseString,
           ITradeChannel channel, GybConfigure config)
        {
            this.channel = channel;
            this.config = config;
            IDictionary<string, object> xmlDic;
            try
            {
                xmlDic = XmlUtils.LoadXmlString(responseString, "packet");
            }
            catch
            {
                throw channel.ThrowInterfaceException(Format_ErrorMessage);
            }
            init(xmlDic);
        }       

        private void init(IDictionary<string, object> xmlDic)
        {
            object value;
            if (xmlDic.TryGetValue("ErrorCode", out value) || value != null)
            {
                ErrorCode = value.ToString();
            }
            if (xmlDic.TryGetValue("ErrorMsg", out value) || value != null)
            {
                ErrorMsg = value.ToString();
            }        
            if (xmlDic.TryGetValue("Signature", out value) || value != null)
            {
                signature = value.ToString();
            }
            if (xmlDic.TryGetValue("Plain", out value) || value != null)
            {
                plain = value.ToString();
                var entityDic = this.AnalyzePlain(plain);
                LoadProperty(entityDic);
            }           
        }

        /// <summary>
        /// 是否成功
        /// </summary>
        public virtual bool IsSuccess()
        {
            return "00".Equals(RespCode);
        }

        /// <summary>
        /// 错误代码
        /// </summary>
        public string ErrorCode { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMsg { get; set; }

        /// <summary>
        /// 响应码(00表示成功)
        /// </summary>
        public string RespCode { get; set; }

        /// <summary>
        /// 签名检查
        /// </summary>
        /// <param name="channel">通道</param>
        /// <param name="config">配置</param>
        /// <returns></returns>
        public bool SignVeryfy()
        {
            if (string.IsNullOrWhiteSpace(plain))
            {
                return false;
            }
            if (string.IsNullOrWhiteSpace(signature))
            {
                return false;
            }
            return SecurityUtils.SignVerify(config.ConfigureInfo, signature, plain);
        }
    }
}
